<!--
 * @Author: Lzg
 * @Date: 2024-05-10 21:00:26
 * @Description: 音频模块
 * @LastEditors: Lzg
 * @LastEditTime: 2024-05-11 21:00:26
-->
<template>
  <div class="wrap" v-loading="loading">
    <audio style="display: none;" ref="audioRef" :src="audioUrl"></audio>
    <el-tabs v-model="formInline.tabActiveName" :stretch="true" class="tabs" @tab-change="tabChange">
      <el-tab-pane label="文字生成" name="text"></el-tab-pane>
      <el-tab-pane label="音频列表" name="audioList"></el-tab-pane>
    </el-tabs>
    <div v-show="formInline.tabActiveName === 'text'">
      <div style="margin: 1rem; width: 100%; height: 100vh">
        <div class="input-class">
          <el-input
              v-model="submitParams.text"
              :maxlength="1000"
              style="width: 90%;"
              placeholder="请输入内容"
              show-word-limit
              class="fixed-height-input"
              type="textarea"
          >
          </el-input>
          <el-tooltip
              class="box-item"
              effect="dark"
              content="一个时钟为0.5s 停顿"
              placement="top-start"
          >
            <el-button class="tooltip" @click="addText">添加间隔</el-button>
          </el-tooltip>
        </div>
        <div class="other-text">其他设置</div>
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="分类">
            <el-select
                v-model="formInline.cat_Type"
                placeholder="请选择"
                clearable
                @change="onSelectChange"
            >
              <el-option v-for="item in formInline.optionList" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="音色">
            <el-select
                v-model="formInline.cat_id"
                placeholder="请选择"
                clearable
            >
              <el-option v-for="item in formInline.optionList2" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>

          <el-form-item>
            <div class="slider-demo-block">
              <span class="demonstration">语速</span>
              <el-slider v-model="submitParams.speech_rate" :min="-5" :max="5" :step="1"/>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="slider-demo-block">
              <span class="demonstration">音调</span>
              <el-slider v-model="submitParams.pitch_rate" :min="-5" :max="5" :step="1"/>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="flex-algin">
              <el-button type="primary" @click="onTrialListening">音色试听</el-button>
              <el-button type="primary" @click="onSubmit">合成音频</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div v-show="formInline.tabActiveName === 'audioList'" class="wrap">
      <div class="search-Header">
        <el-input
            class="input-margin"
            placeholder="请输入上传文件夹的名字"
            v-model="formInline.searchInput"
            clearable
            @clear="handleClear"
            @input="handleInput"
        >
        </el-input>
        <el-button @click="triggerFileUpload" type="primary">上传</el-button>
        <input
            type="file"
            ref="fileInput"
            accept="audio/*"
            style="display: none"
        @change="handleFilesChange"
        />
      </div>
      <div>
        <span class="switch-box">是否开启字幕</span>
        <el-switch @change="dragStart" v-model="formInline.switchStatus"/>
      </div>

      <el-table :data="tableData" max-height="500" style="width: 100%">
        <el-table-column prop="text" label="音频名称" width="200"/>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button link type="primary" size="small">
              <svg v-if="scope.row.isPlay" @click="playhandleClick(scope.row)" t="1715649005088" class="icon"
                   viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4419" width="200"
                   height="200">
                <path
                    d="M512 62.389956c-248.312412 0-449.610044 201.297632-449.610044 449.610044s201.297632 449.610044 449.610044 449.610044 449.610044-201.297632 449.610044-449.610044S760.312412 62.389956 512 62.389956zM786.507004 786.507004c-35.672454 35.672454-77.196173 63.672158-123.416867 83.222423-47.821145 20.22667-98.655927 30.482245-151.09116 30.482245-52.435233 0-103.270015-10.255575-151.09116-30.482245-46.220694-19.549242-87.744413-47.549969-123.416867-83.222423-35.672454-35.672454-63.672158-77.196173-83.222423-123.416867-20.22667-47.821145-30.482245-98.655927-30.482245-151.090137 0-52.435233 10.255575-103.270015 30.482245-151.09116 19.549242-46.220694 47.549969-87.744413 83.222423-123.416867 35.672454-35.672454 77.196173-63.672158 123.416867-83.222423 47.821145-20.22667 98.654904-30.482245 151.09116-30.482245 52.435233 0 103.268992 10.255575 151.09116 30.482245 46.220694 19.549242 87.744413 47.549969 123.416867 83.222423 35.672454 35.672454 63.672158 77.196173 83.222423 123.416867 20.22667 47.821145 30.482245 98.655927 30.482245 151.09116 0 52.435233-10.255575 103.268992-30.482245 151.090137C850.179163 709.310831 822.179458 750.83455 786.507004 786.507004z"
                    p-id="4420"></path>
                <path
                    d="M727.558427 506.975567l-334.355067-252.891707c-3.868097-2.232854-8.702196 0.558725-8.702196 5.024433l0 505.782392c0 4.465708 4.834098 7.257288 8.702196 5.024433l334.355067-252.890684C731.426525 514.791579 731.426525 509.208421 727.558427 506.975567z"
                    p-id="4421"></path>
              </svg>
              <svg v-else @click="stophandleClick(scope.row)" t="1715649098415" class="icon" viewBox="0 0 1030 1024"
                   version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4567" width="200" height="200">
                <path
                    d="M511.999996 0C229.260123 0-4.0e-06 229.238701-4.0e-06 512c0 282.782725 229.238701 512 512 512 282.782725 0 512-229.217275 512-512C1024.021422 229.238701 794.804147 0 511.999996 0zM511.999996 958.842986c-246.786743 0-446.82156-200.056244-446.82156-446.842986 0-246.786743 200.056244-446.82156 446.82156-446.82156 246.829595 0 446.842986 200.034818 446.842986 446.82156C958.864408 758.786743 758.829591 958.842986 511.999996 958.842986z"
                    p-id="4568"></path>
                <path d="M365.102105 328.52762l85.70472 0 0 385.671242-85.70472 0 0-385.671242Z" p-id="4569"></path>
                <path d="M536.511546 328.52762l107.130901 0 0 385.671242-107.130901 0 0-385.671242Z" p-id="4570"></path>
              </svg>
            </el-button>
            <el-button link type="primary" size="small" @click="onDelete(scope.row)">
              <svg t="1685345224620" class="sd-xggj" viewBox="0 0 1024 1024" version="1.1"
                   xmlns="http://www.w3.org/2000/svg" p-id="8489" width="20" height="20">
                <path
                    d="M160 256H96a32 32 0 0 1 0-64h256V95.936a32 32 0 0 1 32-32h256a32 32 0 0 1 32 32V192h256a32 32 0 1 1 0 64h-64v672a32 32 0 0 1-32 32H192a32 32 0 0 1-32-32zm448-64v-64H416v64zM224 896h576V256H224zm192-128a32 32 0 0 1-32-32V416a32 32 0 0 1 64 0v320a32 32 0 0 1-32 32m192 0a32 32 0 0 1-32-32V416a32 32 0 0 1 64 0v320a32 32 0 0 1-32 32"></path>
              </svg>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {reactive, nextTick, ref, onMounted, computed} from 'vue'
import {ElTabPane, ElTabs, TabPaneName} from 'element-plus'
import api from '@/api'
import {storeToRefs} from 'pinia'
import {useControlStore, useCanvasStore, useWidgetStore} from '@/store'
import {wTextSetting} from "@/components/modules/widgets/wText/wTextSetting";
import {
  getDelSound,
  getSubmitSound,
  getSubmitsSound,
  TGetCatListData,
  TGetSoundItemData,
  TGetSoundParam
} from "@/api/audio";
import {ElMessage, ElMessageBox} from 'element-plus'
type TInitType = {
  timbre_id: number
  text: string
  speech_rate: number
  pitch_rate: number
}
const submitParams = reactive<TInitType>({
  timbre_id: 0,
  text: '',
  speech_rate: 0,
  pitch_rate: 0
})
type TForm = {
  user: string
  optionList: TGetCatListData[]
  optionList2: TGetCatListData[]
  searchInput: string
  tabActiveName: string
  cat_Type?: number | string
  cat_id?: number | string
  switchStatus: boolean
  percent: object
}
const formInline = reactive<TForm>({
  user: '',
  percent: {num: 0},
  cat_Type: '',
  cat_id: '',
  searchInput: '',
  tabActiveName: '',
  switchStatus: false,
  optionList: [],
  optionList2: []
})
const audioRef = ref(null)
const loading = ref(false)
const audioUrl = ref('')
const headers = reactive({
  token: sessionStorage.getItem('token')
})
const getTokenFun = () => {
  const data = {
    username: 'zhao',
    password: 'admin888',
  }
  api.audio.getToken(data).then((res) => {
    console.log(res, '====登录接口==167===')
    sessionStorage.setItem('token', res.data.token)
    // sessionStorage.getItem('token')
  })
}
// 获取token
getTokenFun()
// 获取分类
const getCatListFun = () => {
  const data = {
    token: sessionStorage.getItem('token')
  }
  api.audio.getCatList(data).then((res) => {
    formInline.optionList = res.data
  })
}
getCatListFun()

const onSelectChange = (event) => {
  const data = {
    cat_id: event || 1,
    token: sessionStorage.getItem('token')
  }
  api.audio.getTimbreList(data).then(res => {
    formInline.optionList2 = res.data
  })
}
const addText = () => {
  // 文本添加一个"*"作为图标。
  submitParams.text += '*';
}
const replaceStarsWithTime = (text) => {
  return text.replace(/(\*+)/g, function(match, p1) {
    const starCount = match.length;
    switch (starCount) {
      case 1:
        return '<0.5s>';
      case 2:
        return '<1s>';
      case 3:
        return '<1.5s>';
      default:
        return '<' + (0.5 + (starCount - 1) * 0.5) + 's>';
    }
  })
}
const onSubmit = async () => {
  loading.value = true
  let str = submitParams.text
   str = replaceStarsWithTime(str)
  const data = {
    timbre_id: formInline.cat_id,
    text: str,
    speech_rate: submitParams.speech_rate,
    pitch_rate: submitParams.pitch_rate,
    token: sessionStorage.getItem('token')
  }
   const res = await api.audio.getSubmitSound(data)
  ElMessage({
    message: '合成成功',
    type: 'success',
  })
  submitParams.text = ''
  loading.value = false
}
const onTrialListening = () => {
  audioUrl.value = formInline.optionList2.filter(item => item.id == formInline.cat_id)[0].url
  nextTick(() => {
    audioRef.value.play()
  })
}

const handleInput = (value) => {
}
const handleClear = () => {
  formInline.searchInput = ''
}
let tableData = ref([])
const changeStatus = (row, list) => {
  list.forEach(item => {
    if (row.id == item.id && item.isPlay) {
      item.isPlay = false
    } else {
      item.isPlay = true
    }
  })
}
const playhandleClick = (row) => {
  changeStatus(row,tableData.value)
  audioUrl.value = row.url
  nextTick(() => {
    audioRef.value.play()
  })
}
const stophandleClick = (row) => {
  changeStatus(row,tableData.value)
  nextTick(() => {
    audioRef.value.pause()
  })
}

const onDelete = (row) => {
  audioUrl.value = ''
  api.audio.getDelSound({
    sound_id:row.id,
    token: sessionStorage.getItem('token')
  }).then(res=>{
    if (res.code == 200) {
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      loadDesign()
    }
  })
}

const tabChange = (tabName: TabPaneName) => {
  if (tabName === 'audioList') {
    loading.value = true
    loadDesign()
    loading.value = false
  }
}
const loadDesign = async () => {
  const data: TGetSoundParam = {
    token: sessionStorage.getItem('token')
  }
 const res = await api.audio.getSoundList(data)
     tableData.value = res.data.list.map(item=> {
      item.isPlay = true
      return {
        ...item
      }
    })
}
onMounted(() => {
  nextTick(() => {
    formInline.tabActiveName = 'text'
  })
})
const fileInput = ref(null);
const handleFilesChange = async (event) => {
  const files = event.target.files;
  const file = fileInput.value.files[0];
  const formData = new FormData();
  formData.append('file', file);
  // 添加其他参数
  formData.append('file_name', formInline.searchInput);
  formData.append('token', sessionStorage.getItem('token'));
  api.audio.getSubmitsSound(formData).then(res=> {
    ElMessage.success(`文件上传成功`);
    formInline.searchInput = ''
    loadDesign()
  })
};
const triggerFileUpload = () => {
  if (!formInline.searchInput.trim()){
    ElMessage({
      message: '请输入文件名称',
      type: 'wrring',
    })
    return
  }
  fileInput.value.click();
};
const controlStore = useControlStore()
const widgetStore = useWidgetStore()
const { dPage } = storeToRefs(useCanvasStore())
type TBasicTextData = {
  text: string
  fontSize: number
  fontWeight: string
  showMoveable: boolean
}
const selectStach = reactive<TBasicTextData>({
  text: '+ 添加文字',
  fontSize: 120,
  fontWeight: 'normal',
  showMoveable: false
})
const dragStart = (value)=> {
  if (value) {
    selectBasicText(selectStach)
  } else {
    controlStore.setShowMoveable(false)
    widgetStore.deleteWidget()
  }
}
const selectBasicText = (item: TBasicTextData) => {
  controlStore.setShowMoveable(false) // 清理掉上一次的选择
  let setting = JSON.parse(JSON.stringify(wTextSetting))
  setting.text = '双击编辑文字'
  setting.width = item.fontSize * setting.text.length
  setting.fontSize = item.fontSize
  setting.fontWeight = item.fontWeight
  const { width: pW, height: pH } = dPage.value
  setting.left = pW / 2 - item.fontSize * 3
  setting.top = pH / 2 - item.fontSize / 2

  widgetStore.addWidget(setting)
  // store.dispatch('addWidget', setting)
}
defineExpose({
  selectBasicText
})
</script>
<style lang="less" scoped>
.icon {
  width: 20px !important;
  height: 20px !important;
  fill: lawngreen;
}
.infinite-list {
  height: 100%;
  padding-bottom: 150px;
}
.tabs {
  padding: 0.2rem 0;
}
.wrap {
  width: 100%;
  height: 100%;
  overflow: auto;
  //background: red;
}
.input-class {
  position: relative;
}
.fixed-height-input /deep/ .el-textarea__inner {
  height: 240px;
  overflow-y: auto;
  padding-bottom: 40px;
  resize: none;

}
/deep/ .el-input__count {
  bottom: 24px !important;
  background: transparent;
}
.tooltip {
  position: absolute;
  bottom: 15px;
  left: 15px;
  background: transparent;
  border: 1px solid #cccccc;
}
.other-text {
  font-size: 17px;
  font-weight: 600;
  color: #24b9ff;
  margin: 50px 0 25px;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}
.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.flex-algin {
  width: 280px;
  display: flex;
  justify-content: space-around;
}
.slider-demo-block {
  width: 250px;
  display: flex;
  align-items: center;
}
.slider-demo-block .el-slider {
  margin-top: 0;
  margin-left: 12px;
}
.slider-demo-block .demonstration {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  line-height: 44px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 0;
  color: #666666;
}
.slider-demo-block .demonstration + .el-slider {
  flex: 0 0 80%;
}
.input-margin {
  margin-right: 10px;
}
.search-Header {
  display: flex;
  margin: 10px 0 20px;
  /deep/ .el-input__wrapper {
    margin: 0 15px 0 15px;
  }
  padding-right: 15px;
  .btn-color {
    color: #ffffff;
    background: #4f82f2;
  }
}
.switch-box {
  color: #666666;
  margin: 0 15px 0 25px;
}
.pagination-center {
  display: flex;
  justify-content: space-around;
}
.sd-xggj {
  fill: #ff0000;
}
</style>
